package com.example.foodwebbackend.service;

import com.example.foodwebbackend.dto.MerchantFoodDto;
import com.example.foodwebbackend.entity.MerchantFood;
import com.example.foodwebbackend.mapper.MerchantFoodMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MerchantFoodService {

    @Autowired
    private MerchantFoodMapper merchantFoodMapper;

    /**
     * 获取商家的所有菜品
     */
    public List<MerchantFoodDto> getMerchantFoods(Integer merchantId) {
        List<MerchantFood> foods = merchantFoodMapper.findByMerchantId(merchantId);
        return foods.stream().map(this::convertToDto).collect(Collectors.toList());
    }

    /**
     * 根据ID获取菜品
     */
    public MerchantFood getFoodById(Integer foodId) {
        return merchantFoodMapper.findById(foodId);
    }

    /**
     * 添加菜品
     */
    public MerchantFood addFood(MerchantFood food) {
        // 设置默认值
        food.setCreatedTime(LocalDateTime.now());
        food.setUpdatedTime(LocalDateTime.now());
        if (food.getIsActive() == null) {
            food.setIsActive(true);
        }
        if (food.getRating() == null) {
            food.setRating(BigDecimal.ZERO);
        }
        
        merchantFoodMapper.insert(food);
        return food;
    }

    /**
     * 更新菜品
     */
    public MerchantFood updateFood(MerchantFood food) {
        // 检查菜品是否存在且属于该商家
        MerchantFood existingFood = merchantFoodMapper.findById(food.getFoodId());
        if (existingFood == null || !existingFood.getMerchantId().equals(food.getMerchantId())) {
            return null;
        }
        
        food.setUpdatedTime(LocalDateTime.now());
        merchantFoodMapper.update(food);
        return merchantFoodMapper.findById(food.getFoodId());
    }

    /**
     * 删除菜品
     */
    public boolean deleteFood(Integer foodId, Integer merchantId) {
        // 检查菜品是否存在且属于该商家
        MerchantFood existingFood = merchantFoodMapper.findById(foodId);
        if (existingFood == null || !existingFood.getMerchantId().equals(merchantId)) {
            return false;
        }
        
        int result = merchantFoodMapper.deleteById(foodId);
        return result > 0;
    }

    /**
     * 更新菜品状态
     */
    public boolean updateFoodStatus(Integer foodId, Integer merchantId, Boolean isActive) {
        // 检查菜品是否存在且属于该商家
        MerchantFood existingFood = merchantFoodMapper.findById(foodId);
        if (existingFood == null || !existingFood.getMerchantId().equals(merchantId)) {
            return false;
        }
        
        existingFood.setIsActive(isActive);
        existingFood.setUpdatedTime(LocalDateTime.now());
        int result = merchantFoodMapper.update(existingFood);
        return result > 0;
    }

    /**
     * 搜索菜品
     */
    public List<MerchantFood> searchFoods(String keyword) {
        return merchantFoodMapper.searchFoods(keyword);
    }

    /**
     * 获取热门菜品
     */
    public List<MerchantFood> getPopularFoods(Integer limit) {
        return merchantFoodMapper.findPopularFoods(limit);
    }

    /**
     * 获取热门推荐菜品（基于hot_recommendation表）
     */
    public List<MerchantFood> getHotRecommendations(Integer limit) {
        return merchantFoodMapper.findHotRecommendations(limit);
    }

    /**
     * 获取上架的菜品
     */
    public List<MerchantFood> getActiveFoods() {
        return merchantFoodMapper.findActiveFoods();
    }

    /**
     * 获取商家评价数据
     */
    public List<Map<String, Object>> getMerchantReviews(Integer merchantId) {
        return merchantFoodMapper.findMerchantReviews(merchantId);
    }

    /**
     * 根据分类分页获取菜品
     */
    public List<MerchantFood> getFoodsByCategory(Integer categoryId, int offset, Integer size, String search, String sort) {
        return merchantFoodMapper.findFoodsByCategory(categoryId, offset, size, search, sort);
    }

    /**
     * 统计指定分类的菜品数量
     */
    public int countFoodsByCategory(Integer categoryId, String search) {
        return merchantFoodMapper.countFoodsByCategory(categoryId, search);
    }

    /**
     * 分页获取所有菜品
     */
    public List<MerchantFood> getAllFoodsWithPagination(int offset, Integer size, String search, String sort) {
        return merchantFoodMapper.findAllFoodsWithPagination(offset, size, search, sort);
    }

    /**
     * 统计所有菜品数量
     */
    public int countAllFoods(String search) {
        return merchantFoodMapper.countAllFoods(search);
    }

    /**
     * 将MerchantFood实体转换为DTO
     */
    private MerchantFoodDto convertToDto(MerchantFood food) {
        MerchantFoodDto dto = new MerchantFoodDto();
        dto.setFoodId(food.getFoodId());
        dto.setMerchantId(food.getMerchantId());
        dto.setFoodName(food.getFoodName());
        dto.setFoodDescription(food.getFoodDescription());
        dto.setFoodImagePath(food.getFoodImagePath());
        dto.setCategoryId(food.getCategoryId());
        dto.setFoodPrice(food.getPrice()); // price -> foodPrice
        dto.setCreatedTime(food.getCreatedTime());
        dto.setUpdatedTime(food.getUpdatedTime());
        dto.setIsActive(food.getIsActive());
        dto.setTotalReviews(food.getTotalReviews());
        dto.setFoodRating(food.getRating()); // rating -> foodRating
        dto.setMerchantName(food.getMerchantName());
        dto.setCategoryName(food.getCategoryName());
        return dto;
    }
} 